import cv2
import time
import os
import MazeTreasureHunt
import traceback


def MazeProcess(mazeHunt, image):
    try:
        start_time = time.time()
        mazeHunt.LoadImgResource(image)
        lenSum, paths = mazeHunt.Process()
    except Exception as e:
        print("Get Error: " + str(e))
        traceback.print_exc()
        return None
    else:
        end_time = time.time()
        print("Process Run Time: ", end_time - start_time)
        return lenSum, paths


if __name__ == "__main__":
    result = None
    mazeHunt = MazeTreasureHunt.MazeTreasureHunt()
    mazeHunt.SetPlotUtilsEnable(False)  # 关闭绘图
    mazeHunt.SetDebugEnable(True)  # 开启debug imshow
    # 检查环境变量"RASPBERRY_DEVICE"的值
    raspberry_device = os.getenv("RASPBERRY_DEVICE", "").lower() == "true"

    if raspberry_device:
        from picamera import PiCamera
        from picamera.array import PiRGBArray

        camera = PiCamera()
        camera.resolution = (640, 480)
        camera.framerate = 32
        camera.hflip = True
        camera.vflip = True
        rawCapture = PiRGBArray(camera, size=(640, 480))
        # allow the camera to warmup
        time.sleep(0.1)
        # capture frames from the camera
        for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
            image = frame.array
            cv2.imshow("preview src image", image)
            result = MazeProcess(mazeHunt, image)
            if result:
                break

            cv2.waitKey(1)
            rawCapture.truncate(0)
        camera.close()
    else:
        # 直接使用opencv获取摄像头的视频流并显示到屏幕上
        cap = cv2.VideoCapture(0)
        while True:
            ret, frame = cap.read()
            cv2.imshow("preview src image", frame)
            result = MazeProcess(mazeHunt, frame)
            if result:
                break

            cv2.waitKey(1)
        cap.release()
    cv2.destroyAllWindows()
